Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [1]:
# The new version of dataset is only available in the tfds-nightly package.
%pip --no-cache-dir install tfds-nightly --user
# DON'T MISS TO RESTART THE KERNEL
Requirement already satisfied: tfds-nightly in /root/.local/lib/python3.7/site-packages (3.2.0.dev202007120105)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied: attrs>=18.1.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (19.3.0)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.18.2)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Requirement already satisfied: protobuf>=3.6.1 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (3.11.2)
Requirement already satisfied: wrapt in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.11.2)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from protobuf>=3.6.1->tfds-nightly) (41.4.0)
Note: you may need to restart the kernel to use updated packages.
In [2]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub


print('TF version:', tf.__version__)
print('Hub version:', hub.__version__)
print('GPU is', 'available' if tf.test.is_gpu_available() else 'NOT AVAILABLE, RUNNING ON CPU')
print('tf.keras version:', tf.keras.__version__)
TF version: 2.0.0
Hub version: 0.7.0
GPU is available
tf.keras version: 2.2.4-tf
In [3]:
# TODO: Make all other necessary imports.
%matplotlib inline
# display high resolution images
%config InlineBackend.figure_format ='retina'

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

import itertools
import os

# to prevent many filter warining messages from showing in the output
import warnings
warnings.filterwarnings('ignore')

#progress bar won't show in the output
tfds.disable_progress_bar()

# to prevent too many warning messages
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [4]:
# Download data to default local directory "~/tensorflow_datasets"
!python -m tensorflow_datasets.scripts.download_and_prepare --register_checksums=True --datasets=oxford_flowers102
I0712 17:58:24.575472 140450881193728 download_and_prepare.py:201] Running download_and_prepare for dataset(s):
oxford_flowers102
I0712 17:58:24.576893 140450881193728 dataset_info.py:358] Load dataset info from /root/tensorflow_datasets/oxford_flowers102/2.1.1
I0712 17:58:24.587986 140450881193728 download_and_prepare.py:139] download_and_prepare for dataset oxford_flowers102/2.1.1...
I0712 17:58:24.588342 140450881193728 dataset_builder.py:288] Reusing dataset oxford_flowers102 (/root/tensorflow_datasets/oxford_flowers102/2.1.1)
name: "oxford_flowers102"
description: "The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring\nin the United Kingdom. Each class consists of between 40 and 258 images. The images have\nlarge scale, pose and light variations. In addition, there are categories that have large\nvariations within the category and several very similar categories.\n\nThe dataset is divided into a training set, a validation set and a test set.\nThe training set and validation set each consist of 10 images per class (totalling 1020 images each).\nThe test set consists of the remaining 6149 images (minimum 20 per class)."
citation: "@InProceedings{Nilsback08,\n   author = \"Nilsback, M-E. and Zisserman, A.\",\n   title = \"Automated Flower Classification over a Large Number of Classes\",\n   booktitle = \"Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing\",\n   year = \"2008\",\n   month = \"Dec\"\n}"
location {
  urls: "https://www.robots.ox.ac.uk/~vgg/data/flowers/102/"
}
schema {
  feature {
    name: "file_name"
    type: BYTES
    domain: "file_name"
    presence {
      min_fraction: 1.0
      min_count: 1
    }
    shape {
      dim {
        size: 1
      }
    }
  }
  feature {
    name: "image"
    type: BYTES
    presence {
      min_fraction: 1.0
      min_count: 1
    }
    shape {
      dim {
        size: -1
      }
      dim {
        size: -1
      }
      dim {
        size: 3
      }
    }
  }
  feature {
    name: "label"
    type: INT
    presence {
      min_fraction: 1.0
      min_count: 1
    }
    shape {
      dim {
        size: 1
      }
    }
  }
  string_domain {
    name: "file_name"
    value: "image_08133.jpg"
    value: "image_08138.jpg"
    value: "image_08157.jpg"
    value: "image_08173.jpg"
    value: "image_08174.jpg"
    value: "image_08176.jpg"
    value: "image_08179.jpg"
    value: "image_08182.jpg"
    value: "image_08185.jpg"
    value: "image_08187.jpg"
  }
}
splits {
  name: "test"
  statistics {
    num_examples: 6149
    features {
      type: STRING
      string_stats {
        common_stats {
          num_non_missing: 6149
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            type: QUANTILES
          }
          tot_num_values: 6149
        }
        unique: 6149
        top_values {
          value: "image_08189.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08188.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08186.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08184.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08183.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08181.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08180.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08178.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08172.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08171.jpg"
          frequency: 1.0
        }
        avg_length: 15.0
        rank_histogram {
          buckets {
            label: "image_08189.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 1
            high_rank: 1
            label: "image_08188.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 2
            high_rank: 2
            label: "image_08186.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 3
            high_rank: 3
            label: "image_08184.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 4
            high_rank: 4
            label: "image_08183.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 5
            high_rank: 5
            label: "image_08181.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 6
            high_rank: 6
            label: "image_08180.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 7
            high_rank: 7
            label: "image_08178.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 8
            high_rank: 8
            label: "image_08172.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 9
            high_rank: 9
            label: "image_08171.jpg"
            sample_count: 1.0
          }
        }
      }
      path {
        step: "file_name"
      }
    }
    features {
      type: STRING
      string_stats {
        common_stats {
          num_non_missing: 6149
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            type: QUANTILES
          }
          tot_num_values: 6149
        }
        unique: 6147
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 2.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 2.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        avg_length: 42333.9453125
        rank_histogram {
          buckets {
            label: "__BYTES_VALUE__"
            sample_count: 2.0
          }
          buckets {
            low_rank: 1
            high_rank: 1
            label: "__BYTES_VALUE__"
            sample_count: 2.0
          }
          buckets {
            low_rank: 2
            high_rank: 2
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 3
            high_rank: 3
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 4
            high_rank: 4
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 5
            high_rank: 5
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 6
            high_rank: 6
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 7
            high_rank: 7
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 8
            high_rank: 8
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 9
            high_rank: 9
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
        }
      }
      path {
        step: "image"
      }
    }
    features {
      num_stats {
        common_stats {
          num_non_missing: 6149
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 614.9
            }
            type: QUANTILES
          }
          tot_num_values: 6149
        }
        mean: 57.81362823223289
        std_dev: 26.889661542349568
        num_zeros: 20
        median: 60.0
        max: 101.0
        histograms {
          buckets {
            high_value: 10.1
            sample_count: 388.0019
          }
          buckets {
            low_value: 10.1
            high_value: 20.2
            sample_count: 388.00190000000003
          }
          buckets {
            low_value: 20.2
            high_value: 30.299999999999997
            sample_count: 394.1509
          }
          buckets {
            low_value: 30.299999999999997
            high_value: 40.4
            sample_count: 449.4919
          }
          buckets {
            low_value: 40.4
            high_value: 50.5
            sample_count: 855.3258999999999
          }
          buckets {
            low_value: 50.5
            high_value: 60.599999999999994
            sample_count: 621.6638999999999
          }
          buckets {
            low_value: 60.599999999999994
            high_value: 70.7
            sample_count: 418.74690000000004
          }
          buckets {
            low_value: 70.7
            high_value: 80.8
            sample_count: 1187.3719
          }
          buckets {
            low_value: 80.8
            high_value: 90.89999999999999
            sample_count: 812.2829
          }
          buckets {
            low_value: 90.89999999999999
            high_value: 101.0
            sample_count: 633.9619
          }
        }
        histograms {
          buckets {
            high_value: 16.0
            sample_count: 614.9
          }
          buckets {
            low_value: 16.0
            high_value: 33.0
            sample_count: 614.9
          }
          buckets {
            low_value: 33.0
            high_value: 44.0
            sample_count: 614.9
          }
          buckets {
            low_value: 44.0
            high_value: 50.0
            sample_count: 614.9
          }
          buckets {
            low_value: 50.0
            high_value: 60.0
            sample_count: 614.9
          }
          buckets {
            low_value: 60.0
            high_value: 72.0
            sample_count: 614.9
          }
          buckets {
            low_value: 72.0
            high_value: 76.0
            sample_count: 614.9
          }
          buckets {
            low_value: 76.0
            high_value: 83.0
            sample_count: 614.9
          }
          buckets {
            low_value: 83.0
            high_value: 91.0
            sample_count: 614.9
          }
          buckets {
            low_value: 91.0
            high_value: 101.0
            sample_count: 614.9
          }
          type: QUANTILES
        }
      }
      path {
        step: "label"
      }
    }
  }
  shard_lengths: 3074
  shard_lengths: 3075
  num_bytes: 260784877
}
splits {
  name: "train"
  statistics {
    num_examples: 1020
    features {
      type: STRING
      string_stats {
        common_stats {
          num_non_missing: 1020
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            type: QUANTILES
          }
          tot_num_values: 1020
        }
        unique: 1020
        top_values {
          value: "image_08177.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08175.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08167.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08166.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08165.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08164.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08161.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08154.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08148.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08135.jpg"
          frequency: 1.0
        }
        avg_length: 15.0
        rank_histogram {
          buckets {
            label: "image_08177.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 1
            high_rank: 1
            label: "image_08175.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 2
            high_rank: 2
            label: "image_08167.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 3
            high_rank: 3
            label: "image_08166.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 4
            high_rank: 4
            label: "image_08165.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 5
            high_rank: 5
            label: "image_08164.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 6
            high_rank: 6
            label: "image_08161.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 7
            high_rank: 7
            label: "image_08154.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 8
            high_rank: 8
            label: "image_08148.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 9
            high_rank: 9
            label: "image_08135.jpg"
            sample_count: 1.0
          }
        }
      }
      path {
        step: "file_name"
      }
    }
    features {
      type: STRING
      string_stats {
        common_stats {
          num_non_missing: 1020
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            type: QUANTILES
          }
          tot_num_values: 1020
        }
        unique: 1020
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        avg_length: 42545.15625
        rank_histogram {
          buckets {
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 1
            high_rank: 1
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 2
            high_rank: 2
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 3
            high_rank: 3
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 4
            high_rank: 4
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 5
            high_rank: 5
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 6
            high_rank: 6
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 7
            high_rank: 7
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 8
            high_rank: 8
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 9
            high_rank: 9
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
        }
      }
      path {
        step: "image"
      }
    }
    features {
      num_stats {
        common_stats {
          num_non_missing: 1020
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            type: QUANTILES
          }
          tot_num_values: 1020
        }
        mean: 50.5
        std_dev: 29.443448620476957
        num_zeros: 10
        median: 51.0
        max: 101.0
        histograms {
          buckets {
            high_value: 10.1
            sample_count: 109.242
          }
          buckets {
            low_value: 10.1
            high_value: 20.2
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 20.2
            high_value: 30.299999999999997
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 30.299999999999997
            high_value: 40.4
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 40.4
            high_value: 50.5
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 50.5
            high_value: 60.599999999999994
            sample_count: 101.08200000000001
          }
          buckets {
            low_value: 60.599999999999994
            high_value: 70.7
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 70.7
            high_value: 80.8
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 80.8
            high_value: 90.89999999999999
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 90.89999999999999
            high_value: 101.0
            sample_count: 109.242
          }
        }
        histograms {
          buckets {
            high_value: 10.0
            sample_count: 102.0
          }
          buckets {
            low_value: 10.0
            high_value: 20.0
            sample_count: 102.0
          }
          buckets {
            low_value: 20.0
            high_value: 30.0
            sample_count: 102.0
          }
          buckets {
            low_value: 30.0
            high_value: 40.0
            sample_count: 102.0
          }
          buckets {
            low_value: 40.0
            high_value: 51.0
            sample_count: 102.0
          }
          buckets {
            low_value: 51.0
            high_value: 61.0
            sample_count: 102.0
          }
          buckets {
            low_value: 61.0
            high_value: 71.0
            sample_count: 102.0
          }
          buckets {
            low_value: 71.0
            high_value: 81.0
            sample_count: 102.0
          }
          buckets {
            low_value: 81.0
            high_value: 91.0
            sample_count: 102.0
          }
          buckets {
            low_value: 91.0
            high_value: 101.0
            sample_count: 102.0
          }
          type: QUANTILES
        }
      }
      path {
        step: "label"
      }
    }
  }
  shard_lengths: 1020
  num_bytes: 43474584
}
splits {
  name: "validation"
  statistics {
    num_examples: 1020
    features {
      type: STRING
      string_stats {
        common_stats {
          num_non_missing: 1020
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            type: QUANTILES
          }
          tot_num_values: 1020
        }
        unique: 1020
        top_values {
          value: "image_08187.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08185.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08182.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08179.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08176.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08174.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08173.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08157.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08138.jpg"
          frequency: 1.0
        }
        top_values {
          value: "image_08133.jpg"
          frequency: 1.0
        }
        avg_length: 15.0
        rank_histogram {
          buckets {
            label: "image_08187.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 1
            high_rank: 1
            label: "image_08185.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 2
            high_rank: 2
            label: "image_08182.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 3
            high_rank: 3
            label: "image_08179.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 4
            high_rank: 4
            label: "image_08176.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 5
            high_rank: 5
            label: "image_08174.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 6
            high_rank: 6
            label: "image_08173.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 7
            high_rank: 7
            label: "image_08157.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 8
            high_rank: 8
            label: "image_08138.jpg"
            sample_count: 1.0
          }
          buckets {
            low_rank: 9
            high_rank: 9
            label: "image_08133.jpg"
            sample_count: 1.0
          }
        }
      }
      path {
        step: "file_name"
      }
    }
    features {
      type: STRING
      string_stats {
        common_stats {
          num_non_missing: 1020
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            type: QUANTILES
          }
          tot_num_values: 1020
        }
        unique: 1020
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        top_values {
          value: "__BYTES_VALUE__"
          frequency: 1.0
        }
        avg_length: 42256.625
        rank_histogram {
          buckets {
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 1
            high_rank: 1
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 2
            high_rank: 2
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 3
            high_rank: 3
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 4
            high_rank: 4
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 5
            high_rank: 5
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 6
            high_rank: 6
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 7
            high_rank: 7
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 8
            high_rank: 8
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
          buckets {
            low_rank: 9
            high_rank: 9
            label: "__BYTES_VALUE__"
            sample_count: 1.0
          }
        }
      }
      path {
        step: "image"
      }
    }
    features {
      num_stats {
        common_stats {
          num_non_missing: 1020
          min_num_values: 1
          max_num_values: 1
          avg_num_values: 1.0
          num_values_histogram {
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            buckets {
              low_value: 1.0
              high_value: 1.0
              sample_count: 102.0
            }
            type: QUANTILES
          }
          tot_num_values: 1020
        }
        mean: 50.5
        std_dev: 29.443448620476957
        num_zeros: 10
        median: 51.0
        max: 101.0
        histograms {
          buckets {
            high_value: 10.1
            sample_count: 109.242
          }
          buckets {
            low_value: 10.1
            high_value: 20.2
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 20.2
            high_value: 30.299999999999997
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 30.299999999999997
            high_value: 40.4
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 40.4
            high_value: 50.5
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 50.5
            high_value: 60.599999999999994
            sample_count: 101.08200000000001
          }
          buckets {
            low_value: 60.599999999999994
            high_value: 70.7
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 70.7
            high_value: 80.8
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 80.8
            high_value: 90.89999999999999
            sample_count: 100.06200000000001
          }
          buckets {
            low_value: 90.89999999999999
            high_value: 101.0
            sample_count: 109.242
          }
        }
        histograms {
          buckets {
            high_value: 10.0
            sample_count: 102.0
          }
          buckets {
            low_value: 10.0
            high_value: 20.0
            sample_count: 102.0
          }
          buckets {
            low_value: 20.0
            high_value: 30.0
            sample_count: 102.0
          }
          buckets {
            low_value: 30.0
            high_value: 40.0
            sample_count: 102.0
          }
          buckets {
            low_value: 40.0
            high_value: 51.0
            sample_count: 102.0
          }
          buckets {
            low_value: 51.0
            high_value: 61.0
            sample_count: 102.0
          }
          buckets {
            low_value: 61.0
            high_value: 71.0
            sample_count: 102.0
          }
          buckets {
            low_value: 71.0
            high_value: 81.0
            sample_count: 102.0
          }
          buckets {
            low_value: 81.0
            high_value: 91.0
            sample_count: 102.0
          }
          buckets {
            low_value: 91.0
            high_value: 101.0
            sample_count: 102.0
          }
          type: QUANTILES
        }
      }
      path {
        step: "label"
      }
    }
  }
  shard_lengths: 1020
  num_bytes: 43180278
}
supervised_keys {
  input: "image"
  output: "label"
}
version: "2.1.1"
download_size: 344878000

In [5]:
# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()
data, info= tfds.load('oxford_flowers102', as_supervised= True,with_info = True)
In [6]:
# TODO: Create a training set, a validation set and a test set.
#As there's a misorder in the split, I switched between the train and test split
train_ds,validate_ds, test_ds = data['test'],data['validation'], data['train']

tfds.core.DatasetInfo, if with_info is True, then tfds.load will return a tuple (ds, ds_info) containing dataset information (version, features, splits, num_examples,...). Note that the ds_info object documents the entire dataset, regardless of the split requested. Split-specific information is available in ds_info.splits.

Explore the Dataset

In [7]:
# TODO: Get the number of examples in each set from the dataset info.

num_train_examples = info.splits['test'].num_examples
num_validate_examples = info.splits['validation'].num_examples
num_test_examples = info.splits['train'].num_examples

print(num_train_examples)
print(num_validate_examples)
print(num_test_examples)
6149
1020
1020
In [8]:
# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = info.features['label'].num_classes
print(num_classes)
102
In [9]:
print(list(info.splits.keys()))
print(info.splits)
['test', 'train', 'validation']
{'test': <tfds.core.SplitInfo num_examples=6149>, 'train': <tfds.core.SplitInfo num_examples=1020>, 'validation': <tfds.core.SplitInfo num_examples=1020>}
In [10]:
shape_images = info.features['image'].shape
shape_images
Out[10]:
(None, None, 3)
In [11]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
# TODO: Plot 1 image from the training set. 
# Set the title of the plot to the corresponding image label. 

i =1
for image, label in train_ds.take(3):
        print('image',i,':')
        print('data type:',image.dtype)
        print('shape:',image.shape)
        print('label data type:', label.dtype)
        
        image = image.numpy().squeeze()
        label = label.numpy()
        
        plt.imshow(image,cmap = plt.cm.binary)
        plt.colorbar()
        plt.title(label)
        plt.show()
        print('the corresponding label is:', label)
        print('\n')
        i+=1
image 1 :
data type: <dtype: 'uint8'>
shape: (542, 500, 3)
label data type: <dtype: 'int64'>
the corresponding label is: 40


image 2 :
data type: <dtype: 'uint8'>
shape: (748, 500, 3)
label data type: <dtype: 'int64'>
the corresponding label is: 76


image 3 :
data type: <dtype: 'uint8'>
shape: (500, 600, 3)
label data type: <dtype: 'int64'>
the corresponding label is: 42


Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [12]:
import json

with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [13]:
class_names_dict = dict()
for i in class_names:
    class_names_dict[str(int(i)-1)] = class_names[i]
In [14]:
print(class_names_dict)
{'20': 'fire lily', '2': 'canterbury bells', '44': 'bolero deep blue', '0': 'pink primrose', '33': 'mexican aster', '26': 'prince of wales feathers', '6': 'moon orchid', '15': 'globe-flower', '24': 'grape hyacinth', '25': 'corn poppy', '78': 'toad lily', '38': 'siam tulip', '23': 'red ginger', '66': 'spring crocus', '34': 'alpine sea holly', '31': 'garden phlox', '9': 'globe thistle', '5': 'tiger lily', '92': 'ball moss', '32': 'love in the mist', '8': 'monkshood', '101': 'blackberry lily', '13': 'spear thistle', '18': 'balloon flower', '99': 'blanket flower', '12': 'king protea', '48': 'oxeye daisy', '14': 'yellow iris', '60': 'cautleya spicata', '30': 'carnation', '63': 'silverbush', '67': 'bearded iris', '62': 'black-eyed susan', '68': 'windflower', '61': 'japanese anemone', '19': 'giant white arum lily', '37': 'great masterwort', '3': 'sweet pea', '85': 'tree mallow', '100': 'trumpet creeper', '41': 'daffodil', '21': 'pincushion flower', '1': 'hard-leaved pocket orchid', '53': 'sunflower', '65': 'osteospermum', '69': 'tree poppy', '84': 'desert-rose', '98': 'bromelia', '86': 'magnolia', '4': 'english marigold', '91': 'bee balm', '27': 'stemless gentian', '96': 'mallow', '56': 'gaura', '39': 'lenten rose', '46': 'marigold', '58': 'orange dahlia', '47': 'buttercup', '54': 'pelargonium', '35': 'ruby-lipped cattleya', '90': 'hippeastrum', '28': 'artichoke', '70': 'gazania', '89': 'canna lily', '17': 'peruvian lily', '97': 'mexican petunia', '7': 'bird of paradise', '29': 'sweet william', '16': 'purple coneflower', '51': 'wild pansy', '83': 'columbine', '11': "colt's foot", '10': 'snapdragon', '95': 'camellia', '22': 'fritillary', '49': 'common dandelion', '43': 'poinsettia', '52': 'primula', '71': 'azalea', '64': 'californian poppy', '79': 'anthurium', '75': 'morning glory', '36': 'cape flower', '55': 'bishop of llandaff', '59': 'pink-yellow dahlia', '81': 'clematis', '57': 'geranium', '74': 'thorn apple', '40': 'barbeton daisy', '94': 'bougainvillea', '42': 'sword lily', '82': 'hibiscus', '77': 'lotus lotus', '87': 'cyclamen', '93': 'foxglove', '80': 'frangipani', '73': 'rose', '88': 'watercress', '72': 'water lily', '45': 'wallflower', '76': 'passion flower', '50': 'petunia'}
In [15]:
print(class_names_dict['92'])
ball moss
In [16]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
i =1
for image, label in train_ds.take(5):
        
  
        
        image = image.numpy().squeeze()
        label = label.numpy()
      
        plt.imshow(image,cmap = plt.cm.binary)
        plt.colorbar()
      
        plt.title(class_names_dict[str(label)])
        plt.show()
        print('\n')
        i+=1





Create Pipeline

In [17]:
shape_images = info.features['image'].shape
num_classes = info.features['label'].num_classes
print('There are {:,} classes in our dataset'.format(num_classes))
print('The images in our dataset have shape:', shape_images)
There are 102 classes in our dataset
The images in our dataset have shape: (None, None, 3)
In [18]:
# TODO: Create a pipeline for each set.
batch_size = 32
image_size = 224
#change to float and normalize here - resize


def normalize(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (image_size,image_size))
    image /= 255
    return image, label
In [19]:
# batching


training_batches = train_ds.shuffle(num_train_examples//4).map(normalize).batch(batch_size).prefetch(1)
validating_batches = validate_ds.map(normalize).batch(batch_size).prefetch(1)
testing_batches = test_ds.map(normalize).batch(batch_size).prefetch(1)
In [20]:
training_batches
Out[20]:
<PrefetchDataset shapes: ((None, 224, 224, 3), (None,)), types: (tf.float32, tf.int64)>
In [21]:
for image_batch, label_batch in training_batches.take(1):
    print(image_batch.dtype)
    print(image_batch.shape)
    print(label_batch.numpy().size)
    print(label_batch.numpy())
<dtype: 'float32'>
(32, 224, 224, 3)
32
[52 74 75 80 52 95 81 71  9 85 77 27 71 17 87 73 45 83 51 50 10 71 79 40
 76 50  1 64 80 94  6  1]
In [22]:
i = 0
for image_batch, label_bath in training_batches.take(5):
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()
    
    #visualization    
    plt.imshow(images[i], cmap = plt.cm.binary)
    plt.colorbar()
    plt.show()
    print('Label:', labels[i])
    i+=1
Label: 52
Label: 74
Label: 75
Label: 80
Label: 52

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [23]:
# TODO: Build your network.

image_shape = (image_size, image_size, 3)

def build_model():
    # Load the MobileNet pre-trained network from TensorFlow Hub
    module = 'https://tfhub.dev/google/imagenet/mobilenet_v1_050_160/classification/4'

    feature_extractor_layer = hub.KerasLayer(module, input_shape=image_shape, trainable=False)
    
    model = tf.keras.Sequential([feature_extractor_layer,
                                 tf.keras.layers.Dense(600,activation='relu'),
                                 tf.keras.layers.Dropout(0.2),
                                 tf.keras.layers.Dense(300,activation='relu'),
                                 tf.keras.layers.Dropout(0.2),
                                 tf.keras.layers.Dense(num_classes, activation='softmax')
                                ])

    print(model.summary())
    
    return model
In [24]:
# TODO: train your network.
epochs = 30
def train_model():
    model = build_model()
    model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
                  loss='sparse_categorical_crossentropy',
                  metrics=['acc'])
    # Stop training when there is no improvement in the validation loss for 5 consecutive epochs
    early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)

    history = model.fit(training_batches, epochs=epochs, validation_data=validating_batches, callbacks=[early_stopping])
    
    return model, history
In [25]:
model, history = train_model()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1001)              1343049   
_________________________________________________________________
dense (Dense)                (None, 600)               601200    
_________________________________________________________________
dropout (Dropout)            (None, 600)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 300)               180300    
_________________________________________________________________
dropout_1 (Dropout)          (None, 300)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 102)               30702     
=================================================================
Total params: 2,155,251
Trainable params: 812,202
Non-trainable params: 1,343,049
_________________________________________________________________
None
Epoch 1/30
193/193 [==============================] - 28s 147ms/step - loss: 3.8948 - acc: 0.1939 - val_loss: 0.0000e+00 - val_acc: 0.0000e+00
Epoch 2/30
193/193 [==============================] - 21s 108ms/step - loss: 2.3543 - acc: 0.4739 - val_loss: 1.9116 - val_acc: 0.5451
Epoch 3/30
193/193 [==============================] - 22s 112ms/step - loss: 1.5569 - acc: 0.6209 - val_loss: 1.3442 - val_acc: 0.6559
Epoch 4/30
193/193 [==============================] - 21s 108ms/step - loss: 1.1548 - acc: 0.7068 - val_loss: 1.0071 - val_acc: 0.7382
Epoch 5/30
193/193 [==============================] - 21s 110ms/step - loss: 0.9189 - acc: 0.7616 - val_loss: 0.8227 - val_acc: 0.7775
Epoch 6/30
193/193 [==============================] - 21s 110ms/step - loss: 0.7250 - acc: 0.8006 - val_loss: 0.7499 - val_acc: 0.8020
Epoch 7/30
193/193 [==============================] - 21s 108ms/step - loss: 0.6196 - acc: 0.8275 - val_loss: 0.6314 - val_acc: 0.8304
Epoch 8/30
193/193 [==============================] - 21s 108ms/step - loss: 0.5163 - acc: 0.8603 - val_loss: 0.5577 - val_acc: 0.8500
Epoch 9/30
193/193 [==============================] - 21s 107ms/step - loss: 0.4653 - acc: 0.8722 - val_loss: 0.5462 - val_acc: 0.8471
Epoch 10/30
193/193 [==============================] - 21s 108ms/step - loss: 0.4064 - acc: 0.8845 - val_loss: 0.5049 - val_acc: 0.8578
Epoch 11/30
193/193 [==============================] - 21s 108ms/step - loss: 0.3427 - acc: 0.9036 - val_loss: 0.4956 - val_acc: 0.8569
Epoch 12/30
193/193 [==============================] - 21s 108ms/step - loss: 0.3247 - acc: 0.9065 - val_loss: 0.4756 - val_acc: 0.8569
Epoch 13/30
193/193 [==============================] - 21s 109ms/step - loss: 0.2779 - acc: 0.9219 - val_loss: 0.4291 - val_acc: 0.8794
Epoch 14/30
193/193 [==============================] - 21s 108ms/step - loss: 0.2595 - acc: 0.9309 - val_loss: 0.4215 - val_acc: 0.8863
Epoch 15/30
193/193 [==============================] - 21s 108ms/step - loss: 0.2303 - acc: 0.9333 - val_loss: 0.4280 - val_acc: 0.8794
Epoch 16/30
193/193 [==============================] - 21s 107ms/step - loss: 0.2091 - acc: 0.9434 - val_loss: 0.4103 - val_acc: 0.8804
Epoch 17/30
193/193 [==============================] - 21s 109ms/step - loss: 0.1839 - acc: 0.9493 - val_loss: 0.4141 - val_acc: 0.8882
Epoch 18/30
193/193 [==============================] - 21s 110ms/step - loss: 0.1652 - acc: 0.9551 - val_loss: 0.4009 - val_acc: 0.8912
Epoch 19/30
193/193 [==============================] - 21s 110ms/step - loss: 0.1511 - acc: 0.9556 - val_loss: 0.3973 - val_acc: 0.8833
Epoch 20/30
193/193 [==============================] - 21s 108ms/step - loss: 0.1436 - acc: 0.9577 - val_loss: 0.3998 - val_acc: 0.8980
Epoch 21/30
193/193 [==============================] - 21s 108ms/step - loss: 0.1350 - acc: 0.9631 - val_loss: 0.3917 - val_acc: 0.8804
Epoch 22/30
193/193 [==============================] - 21s 108ms/step - loss: 0.1172 - acc: 0.9685 - val_loss: 0.4074 - val_acc: 0.8833
Epoch 23/30
193/193 [==============================] - 21s 109ms/step - loss: 0.1088 - acc: 0.9702 - val_loss: 0.4095 - val_acc: 0.8931
Epoch 24/30
193/193 [==============================] - 21s 108ms/step - loss: 0.1129 - acc: 0.9714 - val_loss: 0.4022 - val_acc: 0.8912
Epoch 25/30
193/193 [==============================] - 21s 108ms/step - loss: 0.1025 - acc: 0.9704 - val_loss: 0.3764 - val_acc: 0.9000
Epoch 26/30
193/193 [==============================] - 21s 108ms/step - loss: 0.0916 - acc: 0.9743 - val_loss: 0.3607 - val_acc: 0.9020
Epoch 27/30
193/193 [==============================] - 21s 108ms/step - loss: 0.0815 - acc: 0.9782 - val_loss: 0.3640 - val_acc: 0.8931
Epoch 28/30
193/193 [==============================] - 21s 108ms/step - loss: 0.0798 - acc: 0.9780 - val_loss: 0.3698 - val_acc: 0.8902
Epoch 29/30
193/193 [==============================] - 21s 108ms/step - loss: 0.0763 - acc: 0.9779 - val_loss: 0.3751 - val_acc: 0.8941
Epoch 30/30
193/193 [==============================] - 21s 109ms/step - loss: 0.0804 - acc: 0.9780 - val_loss: 0.3691 - val_acc: 0.8990
In [26]:
# Check that history.history is a dictionary
print('history.history has type:', type(history.history))

# Print the keys of the history.history dictionary
print('\nThe keys of history.history are:', list(history.history.keys()))
history.history has type: <class 'dict'>

The keys of history.history are: ['loss', 'acc', 'val_loss', 'val_acc']
In [29]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
epochs=30
training_accuracy = history.history['acc']
validation_accuracy = history.history['val_acc']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(epochs)

plt.figure(figsize=(15, 15))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend()
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend()
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [30]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(testing_batches)

print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
32/32 [==============================] - 3s 95ms/step - loss: 0.5095 - acc: 0.8676

Loss on the TEST Set: 0.509
Accuracy on the TEST Set: 86.765%

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [31]:
# TODO: Save your trained model as a Keras model.

model.save('best_model.h5')

Load the Keras Model

Load the Keras model you saved above.

In [32]:
# TODO: Load the Keras model
reloaded_model = tf.keras.models.load_model('best_model.h5',custom_objects={'KerasLayer':hub.KerasLayer})
reloaded_model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1001)              1343049   
_________________________________________________________________
dense (Dense)                (None, 600)               601200    
_________________________________________________________________
dropout (Dropout)            (None, 600)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 300)               180300    
_________________________________________________________________
dropout_1 (Dropout)          (None, 300)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 102)               30702     
=================================================================
Total params: 2,155,251
Trainable params: 812,202
Non-trainable params: 1,343,049
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [33]:
# TODO: Create the process_image function

def process_image(image):
    image = tf.convert_to_tensor(image)
    image = tf.image.resize(image, (image_size,image_size))
    image /= 255
    return image

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [34]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [113]:
# TODO: Create the predict function

def predict(image_path, model, top_k):
    
    image = Image.open(image_path)
    test_image = np.asarray(image)

    test_image = process_image(test_image)

    print(test_image.shape, np.expand_dims(test_image,axis=0).shape)
    prob_pred = model.predict(np.expand_dims(test_image,axis=0))
    prob_pred = prob_pred[0].tolist()

#TODO: make these changes in the command line code as well
    values, indices= tf.math.top_k(prob_pred, k=top_k)
    probs=values.numpy().tolist()
    classes=indices.numpy().tolist()

    return probs, classes
In [114]:
probs, classes = predict('./test_images/wild_pansy.jpg',reloaded_model, 5)
(224, 224, 3) (1, 224, 224, 3)
In [115]:
pred_label_names = [class_names_dict[str(i)] for i in classes]
print("prediction probabilities :\n",probs)
print('prediction classes:\n',classes)
print('prediction labels:\n',pred_label_names)
prediction probabilities :
 [0.9999704360961914, 1.0449204637552612e-05, 7.891001587267965e-06, 7.745301445538644e-06, 1.133574073719501e-06]
prediction classes:
 [51, 64, 47, 17, 61]
prediction labels:
 ['wild pansy', 'californian poppy', 'buttercup', 'peruvian lily', 'japanese anemone']

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [116]:
# TODO: Plot the input image along with the top 5 classes
image_1 = './test_images/cautleya_spicata.jpg'
image_2 = './test_images/hard-leaved_pocket_orchid.jpg'
image_3 = './test_images/orange_dahlia.jpg'
image_4 = './test_images/wild_pansy.jpg'
In [120]:
def plot_image(path, idx):
    ax = plt.subplot(2, 2, idx*2 + 1)
    
    image = Image.open(path)
    test_image = np.asarray(image)
    image = process_image(test_image)
    
    #taking only the image name from the path name
    p_title = path.rsplit('/',1)[-1]
    plt.title(p_title)
    
    plt.imshow(image)
    
    # predicting
    probs, labels = predict(path, model, 5)
    print(probs)
    print(labels)
    
    # Getting names
    label_names = [class_names_dict[str(i)] for i in labels]
    print(label_names)
    
    # Plotting
    ax = plt.subplot(2, 2, idx*2 + 2)
    ax.yaxis.tick_right()
    ax.set_title('Class Probability')
    sns.barplot(x=probs, y=label_names, color=sns.color_palette()[0]);
In [121]:
plt.figure(figsize = (7,10))
plot_image(image_1, 0)
plot_image(image_2, 1)
plt.show()
(224, 224, 3) (1, 224, 224, 3)
[0.99996018409729, 1.011573931464227e-05, 7.526224635512335e-06, 5.784932000096887e-06, 5.094849711895222e-06]
[60, 23, 36, 56, 78]
['cautleya spicata', 'red ginger', 'cape flower', 'gaura', 'toad lily']
(224, 224, 3) (1, 224, 224, 3)
[0.9999994039535522, 2.773160474589531e-07, 5.817679493702599e-08, 3.181945373853523e-08, 2.9565908832296373e-08]
[1, 79, 6, 19, 22]
['hard-leaved pocket orchid', 'anthurium', 'moon orchid', 'giant white arum lily', 'fritillary']
In [122]:
plt.figure(figsize = (7,10))
plot_image(image_3, 0)
plot_image(image_4, 1)
plt.show()
(224, 224, 3) (1, 224, 224, 3)
[0.9991243481636047, 0.0004264973395038396, 0.00019955374591518193, 0.00010015109728556126, 7.166472641984001e-05]
[58, 40, 70, 4, 88]
['orange dahlia', 'barbeton daisy', 'gazania', 'english marigold', 'watercress']
(224, 224, 3) (1, 224, 224, 3)
[0.9999704360961914, 1.0449204637552612e-05, 7.891001587267965e-06, 7.745301445538644e-06, 1.133574073719501e-06]
[51, 64, 47, 17, 61]
['wild pansy', 'californian poppy', 'buttercup', 'peruvian lily', 'japanese anemone']
In [123]:
# printing the output of predict function for image wild pansy
print(probs)
print(classes)
print(pred_label_names)
[0.9999704360961914, 1.0449204637552612e-05, 7.891001587267965e-06, 7.745301445538644e-06, 1.133574073719501e-06]
[51, 64, 47, 17, 61]
['wild pansy', 'californian poppy', 'buttercup', 'peruvian lily', 'japanese anemone']
In [124]:
# checking prediction on a group of images from the testing set

for image_batch, label_batch in testing_batches.take(1):
    ps = model.predict(image_batch)
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

plt.figure(figsize = (10,15))

for n in range(30):
    plt.subplot(6,5,n+1)
    plt.imshow(images[n], cmap = plt.cm.binary)
    color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
    plt.title(class_names_dict[str(np.argmax(ps[n]))], color=color)
    plt.axis('off')